from numpy import *
from os import listdir
from os import getcwd
from os.path import join


def remove_headers(datafile):
    new_datafile = datafile.split('.')[0] + '-done.txt'
    with open(datafile, 'r') as file_org:
        with open(new_datafile, 'w') as file_new:
            for line in file_org:
                if len(line) > 0 and line[0].isdigit():
                    file_new.write(line)


def save_maximum(datafile, output_file):
    data = loadtxt(datafile)
    v = data.max(0)[1:].tolist()
    i = data.argmax(0)[1:].tolist()
    t = data.take(0, axis=1).take(i) * 1000
    
    output_file.write('data-' + datafile + '\n')
    for tmp in xrange(0, 4):
        output_file.write(str(t[tmp] * 1000) + '\t' + str(v[tmp]) + '\n')


def main():
    workspace = getcwd()
    datafiles = listdir(join(workspace, 'testdata'))
    output = 'output'
    datafiles = ['testdata/' + datafile for datafile in datafiles if
                 datafile.endswith('.txt') and not datafile.split('.')[0].endswith('done')]
    file_output = open(output, 'a')
    
    for datafile in datafiles:
        remove_headers(datafile)
        save_maximum(datafile.split('.')[0] + '-done.txt', file_output)


if __name__ == '__main__':
    main()
